import React, { useState, useMemo, useEffect } from 'react';
import { 
  Card, 
  Form, 
  Input, 
  InputNumber, 
  Select, 
  Button, 
  Table, 
  Row, 
  Col, 
  Statistic, 
  Alert, 
  Typography, 
  Space,
  Tag,
  message,
  AutoComplete,
  Spin
} from 'antd';
import { 
  CalculatorOutlined, 
  DownloadOutlined, 
  InfoCircleOutlined,
  TrophyOutlined,
  SearchOutlined,
  SaveOutlined,
  ArrowLeftOutlined
} from '@ant-design/icons';
import { InvestmentCalculator } from '../../../services/investmentCalculator';
import { FundSearchService } from '../../../services/fundSearchService';
import { 
  FundInfo, 
  InvestmentConfig, 
  InvestmentPlan as BaseInvestmentPlan, 
  StrategyType, 
  FundSearchResult,
  EfficiencyMetrics
} from '../../../types/investment';

const { Title, Text, Paragraph } = Typography;
const { Option } = Select;

interface InvestmentPlan extends BaseInvestmentPlan {
  fundInfo: FundInfo;
}

interface FormValues {
  code: string;
  name: string;
  currentPrice: number;
  maxDrawdown: number;
  totalAmount: number;
  buyTimes: number;
  strategy: StrategyType;
}

interface FundOption {
  value: string;
  label: string;
  fund: FundSearchResult;
}

interface InvestmentPlanFormProps {
  onBack: () => void;
  onSave?: (plan: InvestmentPlan) => void;
  initialData?: Partial<FormValues>;
  mode?: 'create' | 'edit' | 'view';
}

const InvestmentPlanForm: React.FC<InvestmentPlanFormProps> = ({
  onBack,
  onSave,
  initialData,
  mode = 'create'
}) => {
  const [form] = Form.useForm<FormValues>();
  const [loading, setLoading] = useState<boolean>(false);
  const [investmentPlan, setInvestmentPlan] = useState<InvestmentPlan | null>(null);
  const [fundSearchLoading, setFundSearchLoading] = useState<boolean>(false);
  const [fundOptions, setFundOptions] = useState<FundOption[]>([]);
  
  const [fundInfo, setFundInfo] = useState<FundInfo>({
    code: initialData?.code || '',
    name: initialData?.name || '',
    currentPrice: initialData?.currentPrice || 0,
    maxDrawdown: initialData?.maxDrawdown || -30,
    currency: 'CNY',
    type: '基金'
  });

  const [config, setConfig] = useState<InvestmentConfig>({
    totalAmount: initialData?.totalAmount || 10000,
    buyTimes: initialData?.buyTimes || 5,
    strategy: (initialData?.strategy || 'pyramid') as StrategyType
  });

  // 在查看模式下自动生成投资计划
  useEffect(() => {
    if (mode === 'view' && initialData) {
      const newFundInfo: FundInfo = {
        code: initialData.code || '',
        name: initialData.name || '',
        currentPrice: initialData.currentPrice || 0,
        maxDrawdown: initialData.maxDrawdown || -30,
        currency: 'CNY',
        type: '基金'
      };
      
      const newConfig: InvestmentConfig = {
        totalAmount: initialData.totalAmount || 10000,
        buyTimes: initialData.buyTimes || 5,
        strategy: (initialData.strategy || 'pyramid') as StrategyType
      };
      
      setFundInfo(newFundInfo);
      setConfig(newConfig);
      
      const basePlan = InvestmentCalculator.generateInvestmentPlan(newFundInfo, newConfig);
      const plan: InvestmentPlan = {
        ...basePlan,
        fundInfo: newFundInfo
      };
      setInvestmentPlan(plan);
    }
  }, [mode, initialData]);

  // 基金搜索功能
  const handleFundSearch = async (searchText: string) => {
    if (!searchText || searchText.length < 2) {
      setFundOptions([]);
      return;
    }

    try {
      setFundSearchLoading(true);
      const results = await FundSearchService.searchFunds(searchText);
      setFundOptions(results.map(fund => ({
        value: fund.code,
        label: `${fund.code} - ${fund.name}`,
        fund: fund
      })));
    } catch (error) {
      console.error('基金搜索失败:', error);
      message.error('基金搜索失败，请稍后重试');
    } finally {
      setFundSearchLoading(false);
    }
  };

  // 选择基金后自动填充信息
  const handleFundSelect = (_value: string, option: FundOption) => {
    const selectedFund = option.fund;
    form.setFieldsValue({
      code: selectedFund.code,
      name: selectedFund.name,
      currentPrice: selectedFund.currentPrice || undefined
    });
    
    setFundInfo(prev => ({
      ...prev,
      code: selectedFund.code,
      name: selectedFund.name,
      currentPrice: selectedFund.currentPrice || 0
    }));
  };

  // 计算投资计划
  const handleGeneratePlan = async () => {
    try {
      setLoading(true);
      const values = await form.validateFields();
      
      const newFundInfo: FundInfo = {
        code: values.code,
        name: values.name,
        currentPrice: values.currentPrice,
        maxDrawdown: values.maxDrawdown,
        currency: 'CNY',
        type: '基金'
      };
      
      const newConfig: InvestmentConfig = {
        totalAmount: values.totalAmount,
        buyTimes: values.buyTimes,
        strategy: values.strategy
      };
      
      setFundInfo(newFundInfo);
      setConfig(newConfig);
      
      const basePlan = InvestmentCalculator.generateInvestmentPlan(newFundInfo, newConfig);
      const plan: InvestmentPlan = {
        ...basePlan,
        fundInfo: newFundInfo
      };
      setInvestmentPlan(plan);
      
      message.success('投资计划生成成功！');
    } catch (error) {
      message.error('请填写完整的基金信息');
    } finally {
      setLoading(false);
    }
  };

  // 保存投资计划
  const handleSavePlan = () => {
    if (!investmentPlan) {
      message.error('请先生成投资计划');
      return;
    }
    
    if (onSave) {
      onSave(investmentPlan);
      message.success('投资计划保存成功！');
    }
  };

  // 效率指标
  const efficiencyMetrics: EfficiencyMetrics | null = useMemo(() => {
    if (investmentPlan) {
      return InvestmentCalculator.calculateEfficiencyMetrics(investmentPlan, investmentPlan.fundInfo);
    }
    return null;
  }, [investmentPlan]);

  // 导出计划
  const handleExportPlan = () => {
    if (!investmentPlan) return;
    
    const planText = generatePlanText(investmentPlan);
    const blob = new Blob([planText], { type: 'text/plain;charset=utf-8' });
    const url = URL.createObjectURL(blob);
    const a = document.createElement('a');
    a.href = url;
    a.download = `${fundInfo.code}_投资计划.txt`;
    document.body.appendChild(a);
    a.click();
    document.body.removeChild(a);
    URL.revokeObjectURL(url);
    
    message.success('投资计划已导出');
  };

  const generatePlanText = (plan: InvestmentPlan): string => {
    const { fundInfo, buyPoints, riskAnalysis } = plan;
    let text = `基金投资计划\n`;
    text += `================\n\n`;
    text += `基金信息：\n`;
    text += `代码：${fundInfo.code}\n`;
    text += `名称：${fundInfo.name}\n`;
    text += `当前价格：${fundInfo.currentPrice} ${fundInfo.currency}\n`;
    text += `历史最大回撤：${fundInfo.maxDrawdown}%\n\n`;
    
    text += `投资配置：\n`;
    text += `总投资金额：${config.totalAmount} ${fundInfo.currency}\n`;
    text += `计划买入次数：${config.buyTimes} 次\n`;
    text += `投资策略：${InvestmentCalculator.getStrategyDescription(config.strategy as StrategyType)}\n\n`;
    
    text += `买入计划：\n`;
    text += `序号\t目标价格\t买入金额\t买入份额\t跌幅\t触发条件\n`;
    buyPoints.forEach(point => {
      text += `${point.order}\t${point.targetPrice}\t${point.buyAmount}\t${point.shares}\t${point.priceDropPercent}%\t${point.triggerCondition}\n`;
    });
    
    text += `\n风险分析：\n`;
    text += `预期平均成本：${plan.averagePrice.toFixed(2)} ${fundInfo.currency}\n`;
    text += `最大可能亏损：${riskAnalysis.maxLoss}%\n`;
    text += `盈亏平衡价格：${riskAnalysis.breakEvenPrice} ${fundInfo.currency}\n`;
    text += `风险等级：${riskAnalysis.riskLevel}\n`;
    
    return text;
  };

  // 买入计划表格列定义
  const columns = [
    {
      title: '序号',
      dataIndex: 'order',
      key: 'order',
      width: 80,
      align: 'center' as const
    },
    {
      title: '目标价格',
      dataIndex: 'targetPrice',
      key: 'targetPrice',
      render: (price: string) => `¥${price}`
    },
    {
      title: '买入金额',
      dataIndex: 'buyAmount',
      key: 'buyAmount',
      render: (amount: string) => `¥${amount}`
    },
    {
      title: '买入份额',
      dataIndex: 'shares',
      key: 'shares',
      render: (shares: string) => `${shares} 份`
    },
    {
      title: '跌幅',
      dataIndex: 'priceDropPercent',
      key: 'priceDropPercent',
      render: (percent: number) => (
        <Tag color={percent === 0 ? 'blue' : percent > 0 ? 'green' : 'red'}>
          {percent > 0 ? `-${percent}` : percent}%
        </Tag>
      )
    },
    {
      title: '触发条件',
      dataIndex: 'triggerCondition',
      key: 'triggerCondition',
      ellipsis: true
    }
  ];

  const getRiskColor = (riskLevel: string): string => {
    const colors: Record<string, string> = {
      '低风险': '#3f8600',
      '中等风险': '#cf1322',
      '较高风险': '#cf1322',
      '高风险': '#cf1322'
    };
    return colors[riskLevel] || '#000';
  };

  return (
    <div className="investment-plan-form">
      <div style={{ marginBottom: 24 }}>
        <Button 
          icon={<ArrowLeftOutlined />} 
          onClick={onBack}
          style={{ marginRight: 16 }}
        >
          返回列表
        </Button>
        <Title level={2} style={{ display: 'inline-block', margin: 0 }}>
          <CalculatorOutlined /> {mode === 'view' ? '查看' : mode === 'edit' ? '编辑' : '新增'}投资计划
        </Title>
      </div>
      
      <Paragraph type="secondary">
        基于历史最大回撤的智能投资策略，帮助您制定科学的分批买入计划（适用于可任意份额买入的公募基金）
      </Paragraph>

      <Row gutter={[24, 24]}>
        {/* 配置表单 */}
        <Col xs={24} lg={8}>
          <Card title="投资配置" size="small">
            <Form
              form={form}
              layout="vertical"
              disabled={mode === 'view'}
              initialValues={{
                code: initialData?.code || '',
                name: initialData?.name || '',
                currentPrice: initialData?.currentPrice || undefined,
                maxDrawdown: initialData?.maxDrawdown || -30,
                totalAmount: initialData?.totalAmount || 10000,
                buyTimes: initialData?.buyTimes || 5,
                strategy: initialData?.strategy || 'pyramid'
              }}
            >
              <Form.Item
                label="基金搜索"
                tooltip="输入基金代码或名称进行搜索"
              >
                <AutoComplete
                  options={fundOptions}
                  onSearch={handleFundSearch}
                  onSelect={handleFundSelect}
                  placeholder="输入基金代码或名称搜索..."
                  notFoundContent={fundSearchLoading ? <Spin size="small" /> : '暂无数据'}
                  suffixIcon={<SearchOutlined />}
                  style={{ width: '100%' }}
                />
              </Form.Item>

              <Form.Item
                label="基金代码"
                name="code"
                rules={[{ required: true, message: '请输入基金代码' }]}
              >
                <Input placeholder="如：000001" />
              </Form.Item>

              <Form.Item
                label="基金名称"
                name="name"
                rules={[{ required: true, message: '请输入基金名称' }]}
              >
                <Input placeholder="如：华夏成长混合" />
              </Form.Item>

              <Form.Item
                label="当前价格"
                name="currentPrice"
                rules={[{ required: true, message: '请输入当前价格' }]}
              >
                <InputNumber
                  style={{ width: '100%' }}
                  placeholder="当前市场价格"
                  min={0}
                  step={0.01}
                  precision={2}
                />
              </Form.Item>

              <Form.Item
                label="历史最大回撤 (%)"
                name="maxDrawdown"
                tooltip="历史上该基金的最大跌幅，用于计算买入区间"
              >
                <InputNumber
                  style={{ width: '100%' }}
                  placeholder="-30"
                  max={0}
                  step={1}
                />
              </Form.Item>

              <Form.Item
                label="总投资金额"
                name="totalAmount"
                rules={[{ required: true, message: '请输入总投资金额' }]}
              >
                <InputNumber
                  style={{ width: '100%' }}
                  placeholder="10000"
                  min={1}
                  step={1000}
                />
              </Form.Item>

              <Form.Item
                label="计划买入次数"
                name="buyTimes"
                rules={[{ required: true, message: '请选择买入次数' }]}
              >
                <InputNumber
                  style={{ width: '100%' }}
                  min={2}
                  max={10}
                  step={1}
                />
              </Form.Item>

              <Form.Item
                label="投资策略"
                name="strategy"
                tooltip="不同策略的资金分配方式不同"
              >
                <Select placeholder="选择投资策略">
                  <Option value="equal">等额投资</Option>
                  <Option value="pyramid">金字塔策略</Option>
                  <Option value="aggressive">激进策略</Option>
                </Select>
              </Form.Item>

              {mode !== 'view' && (
                <Button 
                  type="primary" 
                  block 
                  icon={<CalculatorOutlined />}
                  loading={loading}
                  onClick={handleGeneratePlan}
                >
                  生成投资计划
                </Button>
              )}
            </Form>
          </Card>

          {/* 策略说明 */}
          <Card title="策略说明" size="small" style={{ marginTop: 16 }}>
            <Space direction="vertical" size="small">
              <div>
                <Text strong>等额投资：</Text>
                <br />
                <Text type="secondary">每次买入相同金额，风险分散均匀</Text>
              </div>
              <div>
                <Text strong>金字塔策略：</Text>
                <br />
                <Text type="secondary">价格越低买入越多，适合长期投资</Text>
              </div>
              <div>
                <Text strong>激进策略：</Text>
                <br />
                <Text type="secondary">大幅下跌时重仓买入，高风险高收益</Text>
              </div>
            </Space>
          </Card>
        </Col>

        {/* 投资计划结果 */}
        <Col xs={24} lg={16}>
          {investmentPlan ? (
            <Space direction="vertical" size="large" style={{ width: '100%' }}>
              {/* 概览统计 */}
              <Row gutter={16}>
                <Col span={6}>
                  <Card size="small">
                    <Statistic
                      title="总投资金额"
                      value={investmentPlan.totalInvestment}
                      precision={2}
                      prefix="¥"
                    />
                  </Card>
                </Col>
                <Col span={6}>
                  <Card size="small">
                    <Statistic
                      title="预期份额"
                      value={investmentPlan.expectedShares}
                      precision={0}
                      suffix="份"
                    />
                  </Card>
                </Col>
                <Col span={6}>
                  <Card size="small">
                    <Statistic
                      title="平均成本"
                      value={investmentPlan.averagePrice}
                      precision={2}
                      prefix="¥"
                    />
                  </Card>
                </Col>
                <Col span={6}>
                  <Card size="small">
                    <Statistic
                      title="风险等级"
                      value={investmentPlan.riskAnalysis.riskLevel}
                      valueStyle={{ 
                        color: getRiskColor(investmentPlan.riskAnalysis.riskLevel)
                      }}
                    />
                  </Card>
                </Col>
              </Row>

              {/* 风险分析 */}
              <Card 
                title="风险分析" 
                size="small"
                extra={
                  <Space>
                    {investmentPlan && onSave && mode !== 'view' && (
                      <Button 
                        type="default" 
                        icon={<SaveOutlined />}
                        onClick={handleSavePlan}
                      >
                        保存计划
                      </Button>
                    )}
                    <Button 
                      type="primary" 
                      icon={<DownloadOutlined />}
                      onClick={handleExportPlan}
                    >
                      导出计划
                    </Button>
                  </Space>
                }
              >
                <Row gutter={16}>
                  <Col span={8}>
                    <Statistic
                      title="最大可能亏损"
                      value={investmentPlan.riskAnalysis.maxLoss}
                      precision={2}
                      suffix="%"
                      valueStyle={{ color: '#cf1322' }}
                    />
                  </Col>
                  <Col span={8}>
                    <Statistic
                      title="盈亏平衡价格"
                      value={investmentPlan.riskAnalysis.breakEvenPrice}
                      precision={2}
                      prefix="¥"
                    />
                  </Col>
                  {efficiencyMetrics && (
                    <Col span={8}>
                      <Statistic
                        title="成本优势"
                        value={efficiencyMetrics.costAdvantage}
                        precision={2}
                        suffix="%"
                        valueStyle={{ color: '#3f8600' }}
                        prefix="+"
                      />
                    </Col>
                  )}
                </Row>
              </Card>

              {/* 买入计划表格 */}
              <Card title="分批买入计划" size="small">
                <Table
                  columns={columns}
                  dataSource={investmentPlan.buyPoints}
                  rowKey="order"
                  pagination={false}
                  size="small"
                />
              </Card>

              {/* 投资建议 */}
              <Alert
                message="投资建议"
                description={
                  <ul style={{ margin: 0, paddingLeft: 20 }}>
                    <li>建议设置价格提醒，当基金价格达到目标买入点时及时执行</li>
                    <li>分批投资需要耐心，不要因为短期波动而改变计划</li>
                    <li>定期回顾和调整计划，特别是当基本面发生重大变化时</li>
                    <li>保持足够的现金流，确保能够按计划执行所有买入点</li>
                    <li>考虑设置止损点，当亏损超过预期时及时调整策略</li>
                  </ul>
                }
                type="info"
                icon={<InfoCircleOutlined />}
                showIcon
              />
            </Space>
          ) : (
            <Card>
              <div style={{ textAlign: 'center', padding: '60px 0' }}>
                <TrophyOutlined style={{ fontSize: 64, color: '#d9d9d9' }} />
                <Title level={4} type="secondary">
                  请填写基金信息并生成投资计划
                </Title>
                <Paragraph type="secondary">
                  基于历史回撤数据，为您制定科学的分批投资策略
                </Paragraph>
              </div>
            </Card>
          )}
        </Col>
      </Row>
    </div>
  );
};

export default InvestmentPlanForm;